package com.todd.studentms.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

@WebFilter(value = "/*", dispatcherTypes = {DispatcherType.REQUEST})
public class GlobalFilter implements Filter {

    private static String[] white = {
            ".css",
            ".js",
            ".html",
            ".jpg",
            ".png",
            ".map"
    };

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest old_req, ServletResponse old_res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) old_req;
        HttpServletResponse res = (HttpServletResponse) old_res;
        // 不缓存
        res.setHeader("Pragma", "No-cache");
        res.setHeader("Cache-Control", "no-cache");
        res.setDateHeader("Expires", 0);
        // 设编码
        req.setCharacterEncoding("utf-8");
        res.setCharacterEncoding("utf-8");
        // 输出URI
        String uri = req.getRequestURI();
        boolean isWhite = Arrays.stream(white).anyMatch(s -> uri.endsWith(s));
        if (!isWhite) {
            System.out.println(req.getRequestURI());
        }
        // 放行
        chain.doFilter(req, res);
        if(!isWhite) {
            System.out.println("--------------------------------------------------");
        }
    }

    @Override
    public void destroy() {

    }
}
